package com.wnxy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wnxy.dto.*;
import com.wnxy.model.Manager;
import com.wnxy.service.ManagerService;
import com.wnxy.util.BeanCopyUtil;
import com.wnxy.util.GetRequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class QQController {
    private RestTemplate rt=new RestTemplate();
    private ObjectMapper om=new ObjectMapper();
    @Autowired
    private ManagerService managerService;

//    @GetMapping("/qqbind")
    public void qqLogin(String code) throws IOException {
        HttpServletResponse response = GetRequestUtil.getresponse();
        System.out.println(code);
        String url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=101780702&client_secret=be3cf79b89eafe3f0b8f90462aed8065&code=" + code + "&redirect_uri=http://www.pawntest.com/qqlogin&state=test";
        String value = rt.getForObject(url, String.class);
        System.out.println(value);
        String token=value.substring(value.indexOf("=")+1,value.indexOf("&"));
        System.out.println(token);
        url="https://graph.qq.com/oauth2.0/me?access_token="+token;
       value = rt.getForObject(url, String.class);
        System.out.println(value);
        String openId=value.substring(value.lastIndexOf(":")+2,value.lastIndexOf("\""));
        url="https://graph.qq.com/user/get_user_info?access_token="+token+"&oauth_consumer_key=101780702&openid="+openId;
        String js = rt.getForObject(url, String.class);
        QQInfoDto qq = om.readValue(js, QQInfoDto.class);
        BindDto bd = new BindDto();

        bd.setManagerQqName(qq.getNickname());
        bd.setOpenId(qq.getOpenId());
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf8");
        String json=om.writeValueAsString(bd);
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("<!DOCTYPE html>").append("<html>").append("<head><meta charset=\"utf-8\"></head>")
                .append("<script>").append("window.opener.postMessage('"+json+"','*')")
                .append("</script>")
                .append("<body>").append("<h3 style='text-align:center'>绑定成功 </h3>").append("</body></html>");
        response.getWriter().write(om.writeValueAsString(stringBuffer.toString()));
        response.getWriter().flush();
    }
}
